package com.qf.mp2302.service.impl;

import com.qf.mp2302.entity.Product;
import com.qf.mp2302.mapper.ProductMapper;
import com.qf.mp2302.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    ProductMapper productMapper;

    @Transactional(rollbackFor = Exception.class,
    isolation = Isolation.READ_COMMITTED) // 隔离级别，调整为读已提交
    @Override
    public boolean modprice(Long id, Integer deltaPrice) {

        //1. 根据id查询商品信息
        Product product = productMapper.selectById(id);

        Integer currentPrice = product.getPrice();
        Integer newprice = currentPrice - deltaPrice;

        //2. 修改数据库表
        product.setPrice(newprice);
        int i = productMapper.updateById(product);

        int retrycount = 0;
        //3. 乐观锁的补偿机制，如果出现 i=0的情况，说明出现了并发冲突，重试
        while (i==0 && retrycount<=10){
            Product productAgain = productMapper.selectById(id);
            Integer priceAgain = productAgain.getPrice();
            int newpriceAgain = priceAgain - deltaPrice;
            productAgain.setPrice(newpriceAgain);

            i = productMapper.updateById(productAgain);
            retrycount++;
        }

        return i == 1;
    }
}
